<?php

namespace Admin\Controller;

use Think\Controller;

class BrandController extends PublicController
{

    /*
    *
    * 构造函数，用于导入外部文件和公共方法
    */
    public function _initialize()
    {
        $this->Brand = D('Brand');
        $this->Brand_image = M('brand_image');
    }

    /*
    *
    * 获取、查询品牌数据
    */
    public function index()
    {
        //搜索，根据广告标题搜索
        $brand_name = I("param.brand_name", "", "htmlspecialchars");
        $condition = array();
        if ($brand_name) {
            $condition['name'] = array('LIKE', '%' . $brand_name . '%');
            $this->assign('name', $brand_name);
        }
        /*//分页
        $count   = $this->Brand->where($condition)->count();// 查询满足要求的总记录数
        $Page    = new \Think\Page($count,5);// 实例化分页类 传入总记录数和每页显示的记录数(25)

        //头部描述信息，默认值 “共 %TOTAL_ROW% 条记录”
        $Page->setConfig('header', '<li class="rows">共<b>%TOTAL_ROW%</b>条&nbsp;第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页</li>');
        //上一页描述信息
        $Page->setConfig('prev', '上一页');
        //下一页描述信息
        $Page->setConfig('next', '下一页');
        //首页描述信息
        $Page->setConfig('first', '首页');
        //末页描述信息
        $Page->setConfig('last', '末页');
        $Page->setConfig('theme', '%FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%%HEADER%');

        $show  = $Page->show();// 分页显示输出*/
        define('rows', 15);
        $count = $this->Brand->where($condition)->count();
        $rows = ceil($count / rows);
        $page = (int)$_GET['page'];
        $page < 0 ? $page = 0 : '';
        $limit = $page * rows;
        $page_index = $this->page_index($count, $rows, $page);
        $list = $this->Brand->where($condition)->limit($limit, rows)->select();
        foreach ($list as $key => $value) {
            $brand_image = $this->Brand_image->where('brand_id=' . intval($value['id']))->order('image_order asc')->select();
            $list[$key]['brand_image'] = $brand_image;
        }
        $this->assign('list', $list);
        $this->assign('page_index', $page_index);
        $this->display(); // 输出模板
    }

    /**
     * 更新图片心意卡图片排序
     */
    public function saveImageOrder()
    {
        $imageOrder = $_POST['imageOrder'];
        if(is_array($imageOrder)){
            foreach ($imageOrder as $value){
                if(isset($value['image_id']) && isset($value['image_order'])){
                    $this->Brand_image->where('id = '. $value['image_id'])->data(['image_order' => $value['image_order']])->save();
                }
            }
        }
    }

    /*
    *
    * 跳转添加或修改品牌数据页面
    */
    public function add()
    {
        //如果是修改，则查询对应广告信息
        if (intval($_GET['id'])) {
            $where = "del<1 ";
            $id = intval($_GET['id']);
            $brand_info = $this->Brand->where('id=' . intval($id))->find();
            $brand_image = $this->Brand_image->where('brand_id=' . intval($id))->order("image_order asc")->select();
            $this->assign("list", $brand_image);
            $this->assign('brand_info', $brand_info);
        } else {
            $where = "del<1 ";
            $brand_info['if_show'] = 1;
            $this->assign("brand_info", $brand_info);
        }
        //获取产品列表
        $goods_list = M("product")->where($where)->field("id,brand_id,name,photo_x,price,num")->order("brand_id DESC")->select();
        $this->assign("goods_list", $goods_list);
        $this->display();
    }


    /*
    *
    * 添加或修改品牌信息
    */
    public function save()
    {
        //构建数组
        $data = array();
        $data['name'] = I('post.name');
        $data['if_show'] = I('post.if_show');
        $data['type'] = I('post.type');
        $path = 'brand/' . date('Ymd');

        if (empty($data['name'])) {
            $this->error('参数错误：请填写心意卡名称');
        }
        if (empty($_POST['goods_name'])) {
            $this->error('参数错误：请选择心意卡关联的产品');
        }
        if (empty($_POST['id']) && empty($_FILES['myfile']["tmp_name"][0])) {
            $this->error('参数错误：请上传心意卡图片');
        }

        //保存数据
        if (intval($_POST['id'])) {
            if (!empty($_FILES["myfile"]["tmp_name"])) {
                $this->uploads($path, $_POST['id'], M('brand_image'));
            }
            $data['product_ids'] = implode(',', $_POST['goods_name']);
            $result = $this->Brand->where('id=' . intval($_POST['id']))->data($data)->save();
        } else {
            //保存添加时间
            $data['addtime'] = time();
            $data['product_ids'] = implode(',', $_POST['goods_name']);
            $result = $this->Brand->add($data);
            $this->uploads($path, $result, M('brand_image'));
        }
        //判断数据是否更新成功
        if ($result) {
            $this->success('操作成功.', 'index');
        } else {
            $this->error('操作失败.');
        }
    }


    /**
     * 心意卡图片的删除
     * @author tiedong
     * @date 2018-01-11
     */
    public function del_brand_image()
    {
        $id = intval($_GET['id']);
        $tj_update = $this->Brand_image->where('id=' . $id)->find();
        if (!$tj_update) {
            $this->error('该图片不存在');
            exit();
        }
        $result = $this->Brand_image->where('id=' . $id)->delete();
        if ($result) {
            //删除图片
            $img_url = "Data/UploadFiles/" . $tj_update['brand_photo'];
            if (file_exists($img_url)) {
                @unlink($img_url);
            }
            $this->redirect('add', array('id' => intval($tj_update['brand_id'])));
            exit();
        } else {
            $this->error('操作失败！');
            exit();
        }
    }

    /**
     *
     * 心意卡删除
     */
    public function del()
    {
        //获取广告id，查询数据库是否有这条数据
        $id = intval($_GET['id']);
        $check_info = $this->Brand->where('id=' . intval($id))->find();
        if (!$check_info) {
            $this->error('参数错误！');
            die();
        }

        //修改对应的显示状态
        $up = $this->Brand->where('id=' . intval($id))->delete();
        if ($up) {
            if ($check_info['photo']) {
                $img_url = "Data/" . $check_info['photo'];
                if (file_exists($img_url)) {
                    @unlink($img_url);
                }
            }
            $this->success('操作成功.', 'index');
        } else {
            $this->error('操作失败.');
        }
    }

    /**
     *心意卡的下架
     */
    public function set_xj()
    {
        $id = intval($_GET['id']);
        $check_info = $this->Brand->where('id=' . intval($id))->find();
        if (!$check_info) {
            $this->error('参数错误！');
            die();
        }

        //修改对应的显示状态
        $data = array();
        $data['if_show'] = $check_info['if_show'] == '1' ? 0 : 1;
        $up = $this->Brand->where('id=' . intval($id))->save($data);
        if ($up) {
            $this->redirect('index');
        } else {
            $this->error('操作失败.');
        }
    }

    /**
     *心意卡的上架
     */
    public function set_sj()
    {
        $id = intval($_GET['id']);
        $check_info = $this->Brand->where('id=' . intval($id))->find();
        if (!$check_info) {
            $this->error('参数错误！');
            die();
        }

        //修改对应的显示状态
        $data = array();
        $data['if_show'] = $check_info['if_show'] == '0' ? 1 : 0;
        $up = $this->Brand->where('id=' . intval($id))->save($data);
        if ($up) {
            $this->redirect('index');
        } else {
            $this->error('操作失败.');
        }
    }

    /**
     * 关联产品的移除
     * @author tiedong
     * @date 2017-01-12
     */
    public function del_product()
    {
        $id = intval($_GET['id']);
        $brand_id = intval($_GET['brand_id']);
        $check_info = M("product")->where("id=" . $id)->find();
        if (!$check_info) {
            $this->error("该产品不存在！");
        }
        //修改相应的状态
        $data = array();
        $data['brand_id'] = $check_info['brand_id'] == $brand_id ? 0 : $id;
        $res = M("product")->where("id=" . $id)->save($data);
        if ($res) {
            $this->redirect('add', array('id' => intval($brand_id)));
        } else {
            $this->error('操作失败.');
        }

    }
}